package br.usp.ime.AUN;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import org.apache.lucene.analysis.StopAnalyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.Search;

public class MateriaDAO {

	private EntityManager em;
	private EntityManagerFactory emf;
	ConnectionMysql con;
	Connection dbCon;
	
	public MateriaDAO() {
		//emf = Persistence.createEntityManagerFactory("AUNPU");
		emf=EntityManagerFactoryProvider.getInstance();
		em = emf.createEntityManager();
		con = new ConnectionMysql();
		dbCon = con.getConnection();
		
	}
	
	public void save(Materia materia){
		em.getTransaction().begin();    
		if(materia.getId()!=0l)
			em.merge(materia);                       
		else
			em.persist(materia);
		em.getTransaction().commit();
		
	}
	
	public void delete(Materia object) {
		em.getTransaction().begin();
		em.merge(object);
		em.remove(object);
		em.getTransaction().commit();
	}

	public void delete(long id) {
		Materia object = em.find(Materia.class, id);                
		em.getTransaction().begin();
		em.merge(object);
		em.remove(object);
		em.getTransaction().commit();   
	}
	
	public List<Materia> listAll(){
		em.getTransaction().begin();
		String jpql = "SELECT a FROM Materia a";
		Query query = em.createQuery(jpql);
		em.getTransaction().commit();
		return query.getResultList();
		
	}

	public Materia findById(long id) {
		String jpql = "SELECT a FROM Materia a where a.id=:id";
		Query query = em.createQuery(jpql);
		query.setParameter("id", id);
		List list=query.getResultList();
		if(list.size()==1)
			return (Materia)list.get(0);
		return null;    
	}
	
	public Materia findByTitulo(String titulo) {
		String jpql = "SELECT a FROM Materia a where a.titulo=:titulo";
		Query query = em.createQuery(jpql);
		query.setParameter("titulo", titulo);
		List list=query.getResultList();
		if(list.size()==1)
			return (Materia)list.get(0);
		return null;    
	}	
	
	public void copiaDoBancoDaAUN(){
		PreparedStatement stmt;
		try {
			stmt = (PreparedStatement) dbCon.prepareStatement("SELECT * FROM materia");
			ResultSet rs = (ResultSet) stmt.executeQuery();
			int i =0;
			while(rs.next()
			) {
					/*	
					&& i < 5) {
					 */
				Materia materia = new Materia();
				String codMateria = rs.getString("cod_materia");
				String titulo = rs.getString("titulo");//.replaceAll("<+[A-Z0-9._%+-/ ]+>", " ");
				String corpo = rs.getString("corpo");//.replaceAll("<+[A-Z0-9._%+-/\\\"\'= ]+>", " ");
				
				 while(titulo.isEmpty()){
					System.out.println("!!!Pulei a materia "+codMateria+" pois ela não tinha titulo!");
					rs.next();
					codMateria = rs.getString("cod_materia");
					titulo = rs.getString("titulo");
					corpo = rs.getString("corpo");
				}
				
				materia.setCodMateria(codMateria);
				materia.setTitulo(titulo);
				materia.setCorpo(corpo);
				System.out.println(codMateria+" titulo"+materia.getTitulo());
				this.save(materia);
				i++;
			}  
			rs.close();  
			stmt.close();        
			dbCon.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public List<Materia> buscarNoticias(String searchTerm) {
	    List<Materia> listaMensagens = null;	    
		try {
			FullTextEntityManager fullTextEM = Search.getFullTextEntityManager(em);
			em.getTransaction().begin();	
			Map<String, Float> boosts = new HashMap<String, Float>();
			boosts.put("titulo",5f);
			boosts.put("corpo",3f);
			
			String[] stopWords = {"de","do","da","dos","das","a","o","as","os","na","no","em","la","já","só","um","uma","uns","umas","às"};    
			MultiFieldQueryParser parser = new MultiFieldQueryParser(new String[]{"titulo","corpo"},new StopAnalyzer(stopWords) ,boosts);
			//QueryParser parser = new QueryParser("titulo", new SnowballAnalyzer("Portuguese"));
		    //QueryParser parser = new QueryParser("titulo",new StopAnalyzer(stopWords));
			org.apache.lucene.search.Query query = parser.parse(searchTerm);
			
			javax.persistence.Query persistenceQuery = fullTextEM.createFullTextQuery(query, Materia.class);

			listaMensagens = persistenceQuery.getResultList();

			em.getTransaction().commit();
		} catch (ParseException e) {
			e.printStackTrace();	
		}
		return listaMensagens;

	}

}
